package com.zy.experience_system.controller;

import com.zy.experience_system.form.FileForm;
import com.zy.experience_system.service.FileService;
import com.zy.experience_system.util.ResultUtil;
import com.zy.experience_system.vo.ImageVO;
import com.zy.experience_system.vo.ResultVO;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;


@RestController
@RequestMapping("/file")
public class FileController extends BaseController{

    @Autowired
    FileService fileService;

    // 日志打印
    private Logger log = LoggerFactory.getLogger("FileController");

    // 文件上传 （可以多文件上传）
    @PostMapping("/uploadFile")
    public ResultVO uploadFile(HttpServletRequest request,
                               @RequestParam("file") MultipartFile file,
                               @RequestParam("content") String content,
                               @RequestParam("name") String name,
                               @RequestParam("typeId") String typeId,
                               @RequestParam("testId") Integer testId,
                               @RequestParam("homeworkId") Integer homeworkId
    ) throws Exception {
            FileForm fileForm = new FileForm();
            fileForm.setContent(content);
            fileForm.setFile(file);
            fileForm.setTypeId(typeId);
            fileForm.setName(name);
            fileForm.setHomeworkId(homeworkId);
            fileForm.setTestId(testId);
        try {
            // 上传的文件被保存了
            fileService.save(fileForm,request);
            // 打印日志
            log.info("上传成功");
            // 自定义返回的统一的 JSON 格式的数据，可以直接返回这个字符串也是可以的。
            return ResultUtil.success(null);
        } catch (Exception e) {
            log.error(e.toString());
        }
        return ResultUtil.error("上传错误");
    }

    //上传图片
    @PostMapping("/uploadImage")
    public ResultVO uploadFile(
            @RequestParam("file") MultipartFile file,
            @RequestParam("content") String content,
            @RequestParam("name") String name,
            @RequestParam("typeId") String typeId,
            HttpServletRequest request)throws Exception{
        FileForm fileForm = new FileForm();
        fileForm.setName(name);
        fileForm.setTypeId(typeId);
        fileForm.setFile(file);
        fileForm.setContent(content);
        try {
            ImageVO imageVO = fileService.saveImage(fileForm,request);
            return ResultUtil.success(imageVO);
        } catch (Exception e){
            log.error(e.toString());
        }
        return ResultUtil.error("上传错误");
    }

}
